package com.smart.translator.ui.settings;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.smart.translator.R;
import android.os.Build;
import android.provider.Settings;
import android.content.Intent;
import android.net.Uri;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import com.smart.translator.service.FloatWindowService;
import com.smart.translator.service.KeySettingFloatService;
import android.content.Context;

public class SettingsFragment extends Fragment {
    private SettingsViewModel viewModel;
    private TextView tvUserName;
    // private Switch switchDarkMode; // 去掉深色模式
    // private Spinner spinnerFontSize; // 去掉字体大小
    private Switch switchFloatWindow;
    private Switch switchKeySetting;
    private Button btnLogout;
    private View rootView;
    
    // 广播接收器
    private BroadcastReceiver floatWindowReceiver;
    // 新增：悬浮窗状态同步广播接收器
    private BroadcastReceiver floatWindowStatusReceiver;
    // 新增：全局悬浮窗控制广播接收器
    private BroadcastReceiver floatWindowControlReceiver;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel = new ViewModelProvider(this).get(SettingsViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_settings, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews(view);
        setupObservers();
        setupListeners();
        registerFloatWindowReceiver();
        registerFloatWindowStatusReceiver(); // 新增
        registerFloatWindowControlReceiver(); // 新增
    }

    @Override
    public void onResume() {
        super.onResume();
        // 自动检测悬浮窗权限并启动服务
        if (switchFloatWindow != null && switchFloatWindow.isChecked() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Settings.canDrawOverlays(requireContext())) {
                requireContext().startService(new Intent(requireContext(), FloatWindowService.class));
            }
        }
    }

    private void initViews(View view) {
        tvUserName = view.findViewById(R.id.tv_user_name);
        // switchDarkMode = view.findViewById(R.id.switch_dark_mode); // 去掉深色模式
        // spinnerFontSize = view.findViewById(R.id.spinner_font_size); // 去掉字体大小
        switchFloatWindow = view.findViewById(R.id.switch_float_window);
        switchKeySetting = view.findViewById(R.id.switch_key_setting);
        btnLogout = view.findViewById(R.id.btn_logout);

        // 设置字体大小选择器
        String[] fontSizes = {"小", "中", "大"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
            requireContext(),
            android.R.layout.simple_spinner_item,
            fontSizes
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // spinnerFontSize.setAdapter(adapter); // 去掉字体大小
    }

    private void setupObservers() {
        viewModel.getUserName().observe(getViewLifecycleOwner(), name -> {
            tvUserName.setText(name);
        });

        // viewModel.getDarkMode().observe(getViewLifecycleOwner(), enabled -> { // 去掉深色模式
        //     switchDarkMode.setChecked(enabled);
        // });

        // viewModel.getFontSizeIndex().observe(getViewLifecycleOwner(), index -> { // 去掉字体大小
        //     spinnerFontSize.setSelection(index);
        // });

        viewModel.getFloatWindow().observe(getViewLifecycleOwner(), enabled -> {
            switchFloatWindow.setChecked(enabled);
        });
    }

    private void setupListeners() {
        // switchDarkMode.setOnCheckedChangeListener((buttonView, isChecked) -> { // 去掉深色模式
        //     viewModel.setDarkMode(isChecked);
        // });

        // spinnerFontSize.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() { // 去掉字体大小
        //     @Override
        //     public void onItemSelected(android.widget.AdapterView<?> parent, View view, int position, long id) {
        //         viewModel.setFontSizeIndex(position);
        //     }

        //     @Override
        //     public void onNothingSelected(android.widget.AdapterView<?> parent) {
        //     }
        // });

        switchFloatWindow.setOnCheckedChangeListener((buttonView, isChecked) -> {
            viewModel.setFloatWindow(isChecked);
            if (isChecked) {
                FloatWindowService.requestAndShowFloatWindow(requireContext());
            } else {
                // 关闭悬浮窗服务
                requireContext().stopService(new Intent(requireContext(), FloatWindowService.class));
            }
        });

        switchKeySetting.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                KeySettingFloatService.requestAndStart(requireContext());
            }
        });

        // 添加键位设置区域的点击事件
        View keySettingLayout = rootView.findViewById(R.id.layout_key_setting);
        keySettingLayout.setOnClickListener(v -> {
            // 跳转到键位信息界面
            Intent intent = new Intent(requireContext(), com.smart.translator.ui.keyinfo.KeyInfoActivity.class);
            startActivity(intent);
        });

        btnLogout.setOnClickListener(v -> {
            viewModel.handleLogout();
        });

        // 设置点击事件
        rootView.findViewById(R.id.tv_version).setOnClickListener(v -> {
            viewModel.checkUpdate();
        });

        rootView.findViewById(R.id.tv_about).setOnClickListener(v -> {
            viewModel.showAbout();
        });

        // 添加设备固件更新点击事件
        rootView.findViewById(R.id.layout_firmware_update).setOnClickListener(v -> {
            // 跳转到固件更新界面
            Intent intent = new Intent(requireContext(), com.smart.translator.ui.ota.OtaUpdateActivity.class);
            startActivity(intent);
        });

        // 暂时注释掉VOSK识别点击事件
        /*
        // 添加VOSK识别点击事件
        rootView.findViewById(R.id.layout_vosk_recognition).setOnClickListener(v -> {
            // 跳转到VOSK识别界面
            Intent intent = new Intent(requireContext(), com.smart.translator.ui.voice.VoskDemoActivity.class);
            startActivity(intent);
        });
        */

        rootView.findViewById(R.id.tv_device_info).setOnClickListener(v -> {
            Navigation.findNavController(v).navigate(R.id.nav_device_info);
        });
    }

    private void registerFloatWindowReceiver() {
        floatWindowReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(android.content.Context context, Intent intent) {
                if ("com.smart.translator.FLOAT_WINDOW_CLOSED".equals(intent.getAction())) {
                    // 悬浮窗被关闭，更新开关状态
                    if (switchFloatWindow != null) {
                        switchFloatWindow.setChecked(false);
                        viewModel.setFloatWindow(false);
                    }
                }
            }
        };
        
        IntentFilter filter = new IntentFilter("com.smart.translator.FLOAT_WINDOW_CLOSED");
        LocalBroadcastManager.getInstance(requireContext()).registerReceiver(floatWindowReceiver, filter);
    }

    private void registerFloatWindowStatusReceiver() {
        floatWindowStatusReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(android.content.Context context, Intent intent) {
                if ("com.smart.translator.FLOAT_WINDOW_STATUS_CHANGED".equals(intent.getAction())) {
                    boolean show = intent.getBooleanExtra("show", false);
                    if (switchFloatWindow != null) {
                        switchFloatWindow.setChecked(show);
                        viewModel.setFloatWindow(show);
                    }
                }
            }
        };
        IntentFilter filter = new IntentFilter("com.smart.translator.FLOAT_WINDOW_STATUS_CHANGED");
        LocalBroadcastManager.getInstance(requireContext()).registerReceiver(floatWindowStatusReceiver, filter);
    }

    private void registerFloatWindowControlReceiver() {
        floatWindowControlReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("com.smart.translator.ACTION_FLOAT_WINDOW_CONTROL".equals(intent.getAction())) {
                    boolean show = intent.getBooleanExtra("show", true);
                    if (switchFloatWindow != null) {
                        switchFloatWindow.setChecked(show); // 触发开关逻辑
                    }
                }
            }
        };
        IntentFilter filter = new IntentFilter("com.smart.translator.ACTION_FLOAT_WINDOW_CONTROL");
        requireContext().registerReceiver(floatWindowControlReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (floatWindowReceiver != null) {
            LocalBroadcastManager.getInstance(requireContext()).unregisterReceiver(floatWindowReceiver);
            floatWindowReceiver = null;
        }
        if (floatWindowStatusReceiver != null) {
            LocalBroadcastManager.getInstance(requireContext()).unregisterReceiver(floatWindowStatusReceiver);
            floatWindowStatusReceiver = null;
        }
        if (floatWindowControlReceiver != null) {
            requireContext().unregisterReceiver(floatWindowControlReceiver);
            floatWindowControlReceiver = null;
        }
    }
} 